<script setup>
import { useCounterStore } from "./stores/counter";

const store = useCounterStore();

console.log("pinia 实例", store);
const handleClick = () => {
  console.log("直接修改状态");
  store.count++;
};
const handleClick2 = () => {
  console.log("通过actions修改状态");
  store.increment();
};

const { increment } = store;
const handleClick3 = () => {
  increment();
};

const handleClick4 = () => {
  const fruits = [...store.fruits, "jjjjjj"];
  const count = store.count++;
  store.$patch({
    count,
    fruits,
  });
};

const handleClick5 = () => {
  store.$patch(() => {
    store.fruits = [...store.fruits, "jjjjjj"];
    store.count++;
  });
};

const handleClick6 = () => {
  store.$reset();
};

const handleClick7 = () => {
  handleClick();
  store.$subscribe((mutation, state) => {
    console.log("$subscribe", mutation, state);
  });
};
store.$onAction(({ after, onError, name }) => {
  console.log("$onAction", name);
  after((result) => {
    console.log("状态更新完毕1", result);
  });
  after((result) => {
    console.log("状态更新完毕2", result);
  });
  onError(() => {
    console.log("onError");
  });
});

const handleClick8 = () => {
  increment();
  setTimeout(() => {
    store.$dispose();
  }, 3000);
};

const handleClick9 = () => {
  store.$state = { count: 100, fruits: [] };
};
</script>

<template>
  <div>
    <h1>state.count: {{ store.count }}</h1>
    <h1>getters.doubleCount: {{ store.doubleCount }}</h1>

    <button @click="handleClick">直接修改状态</button>
    <button @click="handleClick2">通过actions修改状态</button>
    <button @click="handleClick3">通过actions修改状态</button>
    <button @click="handleClick4">$patch传递对象</button>
    <button @click="handleClick5">$patch传递函数</button>
    <button @click="handleClick6">$reset</button>
    <button @click="handleClick7">$subscribe</button>
    <button @click="handleClick8">$dispose</button>
    <button @click="handleClick9">$state</button>
    <div v-for="item in store.fruits" :key="item">
      {{ item }}
    </div>
  </div>
</template>

<style></style>
